# 虚拟邮箱: 线路1
import requests
import random
import string
import time

class VirtualEmailLine1:
    def __init__(self):
        self.base_url: str = "https://api.mail.tm/"
        self.headers: dict = {
            'accept': 'application/json',
            'accept-language': 'zh-CN,zh;q=0.9',
            'authorization': 'Bearer',
            'cache-control': 'no-cache',
            'origin': 'https://internxt.com',
            'pragma': 'no-cache',
            'priority': 'u=1, i',
            'referer': 'https://internxt.com/',
            'sec-ch-ua': '"Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'cross-site',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36',
        }
        self.domain_suffix: str = None
        self.account: str = None
        self.password: str = None
    
    # 内部方法 随机生成 n个长度的 数字+小写字母
    def _random_string(self, n: int) -> str:
        return ''.join(random.choices(string.ascii_lowercase + string.digits, k=n))

    # 内部方法, 获取虚拟邮箱域名后缀
    def _get_domain_suffix(self) -> dict:
        params: dict = {
            'page': '1',
        }
        response: dict = requests.get(self.base_url + 'domains', params=params, headers=self.headers).json()
        """
        [{'id': '683e285734eb9ac6bea7bca6', 'domain': 'punkproof.com', 'isActive': True, 'isPrivate': False, 'createdAt': '2025-06-02T00:00:00+00:00', 'updatedAt': '2025-06-02T00:00:00+00:00'}]
        """
        # 把域名挂载在全局变量中
        self.domain_suffix = response[0]['domain']
        return response[0]

    # 内部方法, 更新(获取)Token
    def _update_token(self) -> dict:
        json_data: dict = {
            'address': self.account,
            'password': self.password,
        }

        response: dict = requests.post(self.base_url + 'token', headers=self.headers, json=json_data).json()
        """
        {
            "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE3NDk1NDcwOTMsInJvbGVzIjpbIlJPTEVfVVNFUiJdLCJhZGRyZXNzIjoibXhkOXVAcHVua3Byb29mLmNvbSIsImlkIjoiNjg0N2Y4NTRhNjY4MGUwOTNkMDBjMzk5IiwibWVyY3VyZSI6eyJzdWJzY3JpYmUiOlsiL2FjY291bnRzLzY4NDdmODU0YTY2ODBlMDkzZDAwYzM5OSJdfX0.UE6siTGIa1r-PKFq7I0IIDfWLeGBHy8uffN2LdSOaB6lfm_kuE7lCzOkvfJcoEo-GNX47lhfUKMD4IL7xHt-5A",
            "@id": "/accounts/6847f854a6680e093d00c399",
            "id": "6847f854a6680e093d00c399"
        }
        """
        self.headers['authorization'] = f'Bearer {response["token"]}'
        return response

    # 内部方法, 创建账号
    def _create_account(self) -> dict:
        # 判断全局变量中是否存在域名后缀
        if not self.domain_suffix:
            self._get_domain_suffix()
        self.account: str = f'{self._random_string(6)}@{self.domain_suffix}'
        self.password: str = self._random_string(8)
        json_data: dict = {
            'address': self.account,
            'password': self.password,
        }
        response: dict = requests.post(self.base_url + 'accounts', headers=self.headers, json=json_data).json()
        """
        {'id': '6847fbc54d7d959f5d0499c5', 'address': '4nwjdr@punkproof.com', 'quota': 40000000, 'used': 0, 'isDisabled': False, 'isDeleted': False, 'createdAt': '2025-06-10T09:32:53+00:00', 'updatedAt': '2025-06-10T09:32:53+00:00'}
        """
        # 账号创建完毕后, 更新Token
        self._update_token()
        return response

    # 内部函数, 获取信息
    def _get_messages(self) -> dict:
        
        params: dict = {
            'page': '1',
        }
        response: dict = requests.get(self.base_url + 'messages', params=params, headers=self.headers).json()
        if len(response) > 0:
            return (True, response[0])
        else:
            return (False, response)
        return (False, response)

    # 内部函数, 获取邮件内容
    def _get_message_content(self, message_id: str) -> dict:
        response: dict = requests.get(self.base_url + f'messages/{message_id}/download', headers=self.headers).json()
        return response
    
    # 主函数, 多封邮件获取
    def VirtualEmailLine1Main_Multi(self, sleep_time: int = 1, max_get_messages: int = 2):
        """
        参数:
            sleep_time: 每次获取信息间隔时间, 单位: 秒
            max_get_messages: 获取邮件的最大数量, 超过该数量后, 程序将结束
        """
        account_info: dict = self._create_account()
        email_info: list = []
        get_messages_count: int = 0
        while get_messages_count < max_get_messages: # 获取邮件数量小于最大获取数量时, 循环获取
            message_info: dict = self._get_messages()
            if message_info[0]:
                # 判断数据是否相同
                if len(email_info) > 0:
                    if message_info[1] in email_info:
                        # 如果数据相同, 则不进行处理
                        continue
                else:
                    print(f"账号: {self.account} 没有最新信息")
                get_messages_count += 1
                email_info.append(message_info[1])
                yield message_info[1]
            else:
                print(f"账号: {self.account} 没有最新信息")
                yield None
            time.sleep(sleep_time)

    # 主函数, 单封邮件获取
    def VirtualEmailLine1Main_Single(self, sleep_time: int = 1):
        """
        参数:
            sleep_time: 每次获取信息间隔时间, 单位: 秒
        """
        account_info: dict = self._create_account()
        while True:
            message_info: dict = self._get_messages()
            if message_info[0]:
                print(f"最新信息: {message_info[1]}")
                return message_info[1]
                break
            else:
                print(f"账号: {self.account} 没有最新信息")
            time.sleep(sleep_time)

if __name__ == '__main__':
    line1 = VirtualEmailLine1()
    line1.VirtualEmailLine1Main_Single()